/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.api.sharedpreferences;

import ohos.data.preferences.Preferences;

/**
 * 抽象字段
 *
 * @param <T> 泛型
 * @since 2021-07-19
 */
public abstract class AbstractPrefField<T> {
    /**
     * 默认值
     */
    protected final T defaultValue;
    /**
     * 参数设置
     */
    protected final Preferences sharedPreferences;
    /**
     * 键
     */
    protected final String key;

    /**
     * 构造参数
     *
     * @param sharedPreferences 预设
     * @param key 键
     * @param defaultValue 默认值
     */
    public AbstractPrefField(Preferences sharedPreferences, String key, T defaultValue) {
        this.sharedPreferences = sharedPreferences;
        this.key = key;
        this.defaultValue = defaultValue;
    }

    /**
     * 是否存在
     *
     * @return boolean是否存在
     */
    public final boolean exists() {
        return sharedPreferences.hasKey(key);
    }

    /**
     * 获取键
     *
     * @return String 键值
     */
    public String key() {
        return this.key;
    }

    /**
     * 获取
     *
     * @return T 泛型
     */
    public final T get() {
        return getOr(defaultValue);
    }

    /**
     * 获取Or
     *
     * @param defaultValue 默认值
     * @return T 泛型
     */
    public abstract T getOr(T defaultValue);

    /**
     * 保存值
     *
     * @param value 值
     */
    public final void put(T value) {
        putInternal((value == null) ? defaultValue : value);
    }

    /**
     * 存放内部
     *
     * @param value 值
     */
    protected abstract void putInternal(T value);

    /**
     * 移除
     */
    public final void remove() {
        edit().delete(key);
        apply(edit());
    }

    /**
     * 编辑
     *
     * @return Preferences 预设
     */
    protected Preferences edit() {
        return sharedPreferences;
    }

    /**
     * 申请
     *
     * @param editor 预设
     */
    protected final void apply(Preferences editor) {
        SharedPreferencesCompat.apply(editor);
    }
}
